package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ciei.dpagm.common.enums.*;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.*;
import com.ciei.dpagm.mapper.DriverLibraryMapper;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.FileUtils;
import com.ciei.dpagm.util.JsonUtil;
import com.ciei.dpagm.util.PageParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author wangyan
 * @date 2023/05/08
 */
@Service
public class DriverLibraryService extends BaseService<DriverLibraryMapper, DriverLibrary> {

    @Value("${baseFilePath}")
    private String baseFilePath;

    @Autowired
    private FilesService filesService;

    @Autowired
    private ChipService chipService;

    @Autowired
    private DriverLibraryDirectoryService driverLibraryDirectoryService;

    @Autowired
    private ChipParameterService chipParameterService;

    @Autowired
    private ChipControlModeService chipControlModeService;

    @Autowired
    private ChipControlModeInterfaceService chipControlModeInterfaceService;

    @Autowired
    private ChipControlModeInterfaceTypeService chipControlModeInterfaceTypeService;

    @Autowired
    private FormPropertyDefinitionService formPropertyDefinitionService;

    @Autowired
    private FormLayoutService formLayoutService;

    @Autowired
    private RuleSetService ruleSetService;

    @Autowired
    private RuleService ruleService;

    @Autowired
    private ConditionService conditionService;

    /**
     * 获取驱动库列表
     * @param pageParam
     * @return
     */
    public JSONObject loadGrid(PageParam pageParam){
        JSONObject resultData = new JSONObject();
        Map<String, Object> params = pageParam.getParams();
        int currentPage = pageParam.getCurrentPage();
        int pageSize = pageParam.getPageSize();
        QueryWrapper<Chip> chipQueryWrapper = chipService.getFormSearchWrapper(params, new String[]{"displayName","model"}, new String[]{"type","displayCategory"}, null, null);
        List<Chip> chipList = chipService.list(chipQueryWrapper);
        if (chipList.isEmpty()){
            return JsonUtil.getSuccess("").fluentPut(APP.DATA,resultData);
        }
        List<Integer> chipIdList = chipList.stream().map(Chip::getChipId).collect(Collectors.toList());
        QueryWrapper<DriverLibrary> driverLibraryQueryWrapper = new QueryWrapper<>();
        driverLibraryQueryWrapper.lambda().in(DriverLibrary::getChipId,chipIdList);
        driverLibraryQueryWrapper.lambda().orderByDesc(DriverLibrary::getDriverLibraryId);
        IPage<DriverLibrary> page = findPageVue(currentPage,pageSize,driverLibraryQueryWrapper);
        List<DriverLibrary> driverLibraryList = page.getRecords();
        JSONArray driverLibraryArray = new JSONArray();
        for (DriverLibrary driverLibrary : driverLibraryList){
            Chip chip = chipList.stream().filter(e ->e.getChipId().equals(driverLibrary.getChipId())).findFirst().orElse(null);
            JSONObject driverLibraryData = packageDriverData(driverLibrary,chip);
            driverLibraryArray.add(driverLibraryData);
        }
        resultData.put(APP.DATA, driverLibraryArray);
        resultData.put(APP.TOTAL_COUNT, page.getTotal());
        resultData.put(APP.CURRENT_PAGE, page.getCurrent());
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,resultData);
    }

    /**
     * 获取单个被控驱动信息
     * @param query
     * @return
     */
    public JSONObject getOneSlaveDriverInfo(JSONObject query){
        JSONObject driverLibraryData = new JSONObject();
        Integer driverLibraryId = query.getInteger("driverLibraryId");
        DriverLibrary driverLibrary = findById(driverLibraryId);
        if (driverLibrary == null){
            return JsonUtil.getSuccess("").fluentPut(APP.DATA,driverLibraryData);
        }
        Chip chip = chipService.findById(driverLibrary.getChipId());
        if (chip == null){
            return JsonUtil.getSuccess("").fluentPut(APP.DATA,driverLibraryData);
        }
        driverLibraryData = packageDriverData(driverLibrary,chip);
        List<Files> filesList = filesService.getFileList(Arrays.asList(FileRelationTypeEnum.DRIVER_DEFINITION.getRelationTypeId(),FileRelationTypeEnum.H_HEADER.getRelationTypeId(),FileRelationTypeEnum.C_SOURCE.getRelationTypeId(),FileRelationTypeEnum.DRIVER_DOCUMENTATION.getRelationTypeId(),FileRelationTypeEnum.OTHER_DRIVER.getRelationTypeId()),driverLibraryId);
        List<Files> driverDefinitionFiles = filesList.stream().filter(e ->e.getRelationId().equals(driverLibrary.getDriverLibraryId()) && e.getRelationTypeId().equals(FileRelationTypeEnum.DRIVER_DEFINITION.getRelationTypeId())).collect(Collectors.toList());
        driverLibraryData.put("driverDefinitionFiles",driverDefinitionFiles);
        List<Files> hHeaderFiles = filesList.stream().filter(e ->e.getRelationId().equals(driverLibrary.getDriverLibraryId()) && e.getRelationTypeId().equals(FileRelationTypeEnum.H_HEADER.getRelationTypeId())).collect(Collectors.toList());
        driverLibraryData.put("hHeaderFiles",hHeaderFiles);
        List<Files> cSourceFiles = filesList.stream().filter(e ->e.getRelationId().equals(driverLibrary.getDriverLibraryId()) && e.getRelationTypeId().equals(FileRelationTypeEnum.C_SOURCE.getRelationTypeId())).collect(Collectors.toList());
        driverLibraryData.put("cSourceFiles",cSourceFiles);
        List<Files> driverDocumentationFiles = filesList.stream().filter(e ->e.getRelationId().equals(driverLibrary.getDriverLibraryId()) && e.getRelationTypeId().equals(FileRelationTypeEnum.DRIVER_DOCUMENTATION.getRelationTypeId())).collect(Collectors.toList());
        driverLibraryData.put("driverDocumentationFiles",driverDocumentationFiles);
        List<Files> otherDriverFiles = filesList.stream().filter(e ->e.getRelationId().equals(driverLibrary.getDriverLibraryId()) && e.getRelationTypeId().equals(FileRelationTypeEnum.OTHER_DRIVER.getRelationTypeId())).collect(Collectors.toList());
        driverLibraryData.put("otherDriverFiles",otherDriverFiles);
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,driverLibraryData);
    }

    /**
     * 组装驱动数据
     * @param chip
     * @return
     */
    public JSONObject packageDriverData(DriverLibrary driverLibrary,Chip chip){
        JSONObject driverLibraryData = new JSONObject();
        driverLibraryData.put("driverLibraryId",driverLibrary.getDriverLibraryId());
        driverLibraryData.put("chipType",driverLibrary.getType());
        driverLibraryData.put("displayName",chip.getDisplayName());
        driverLibraryData.put("displayCategory",chip.getDisplayCategory());
        driverLibraryData.put("manufacturer",chip.getManufacturer());
        driverLibraryData.put("compatible",ChipTypeEnum.MASTER.getType().equals(chip.getType()) ? chip.getCompatible() : driverLibrary.getCompatible());
        driverLibraryData.fluentPut("model",chip.getModel() == null ? "" : chip.getModel());
        return driverLibraryData;
    }

    /**
     * 根据芯片类别加载芯片树
     * @return
     */
    public JSONObject loadTreeByCategory(JSONObject query){
        Integer chipType = query.getInteger("chipType");
        List<Integer> chipIdList = findByProperty(DriverLibrary::getType,chipType).stream().map(DriverLibrary::getChipId).collect(Collectors.toList());
        JSONArray jsonArray = chipService.loadTreeByCategory(chipType);
        if (ChipTypeEnum.MASTER.getType().equals(chipType)){
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject categoryData = jsonArray.getJSONObject(i);
                JSONArray children = categoryData.getJSONArray("children");
                for (int j = 0; j < children.size(); j++) {
                    JSONObject chipData = children.getJSONObject(j);
                    Integer chipId = chipData.getInteger("value");
                    if (chipIdList.contains(chipId)){
                        chipData.put("disabled",true);
                    }else {
                        chipData.put("disabled",false);
                    }
                }
            }
        }
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,jsonArray);
    }

    /**
     * 新增驱动库
     * @param data
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject add(JSONObject data, Users currentUser){
        Integer chipType = data.getInteger("chipType");
        Integer chipId = data.getInteger("chipId");
        Chip chip = chipService.findById(chipId);
        if (chip == null){
            return JsonUtil.getFail(ErrorCodeEnum.INVALID_PARAM,"找不到对应的芯片数据!");
        }
        if (ChipTypeEnum.MASTER.getType().equals(chipType)){
            if (isDuplicateByCondition(chipType,chipId,null,null)){
                return JsonUtil.getFail(ErrorCodeEnum.DUPLICATE_DATA,"主控工程已存在!");
            }
        }
        String compatible = null;
        JSONObject driverData = null;
        if (ChipTypeEnum.SLAVE.getType().equals(chipType)){
            driverData = parseJsonFile(data);
            if (driverData == null){
                return JsonUtil.getFail(ErrorCodeEnum.IMPORT_CONTENT_ERROR);
            }
            compatible = StringUtils.join(driverData.getJSONArray("compatible"),",");
            if (isDuplicateByCondition(chipType,chipId,compatible,null)){
                return JsonUtil.getFail(ErrorCodeEnum.DUPLICATE_DATA,"该芯片驱动范围已存在!");
            }
        }
        Integer userId = currentUser.getUserId();
        DriverLibrary driverLibrary = new DriverLibrary();
        driverLibrary.setType(chipType);
        driverLibrary.setChipId(chipId);
        driverLibrary.setCompatible(compatible);
        driverLibrary.setCreatorId(userId);
        save(driverLibrary);
        if (ChipTypeEnum.MASTER.getType().equals(chipType)){
            driverLibraryDirectoryService.createDirectory(0,chip.getModel(), IsNotEnum.NOT.getId(),driverLibrary.getDriverLibraryId());
        }
        if (ChipTypeEnum.SLAVE.getType().equals(chipType)){
            saveDriverInfo(chip,driverLibrary,driverData,userId);
            filesService.saveFiles(data.getJSONArray("driverDefinitionFiles"),userId,FileRelationTypeEnum.DRIVER_DEFINITION.getRelationTypeId(),driverLibrary.getDriverLibraryId());
            List<RuleSet> ruleSetList = ruleSetService.findByProperty(RuleSet::getDriverLibraryId, driverLibrary.getDriverLibraryId());
            return ruleSetService.getParameterConfigurationRuleSetList(ruleSetList);
        }
        return JsonUtil.getSuccess("");
    }

    /**
     * 修改驱动库
     * @param data
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateByFile(JSONObject data, Users currentUser) {
        Integer driverLibraryId = data.getInteger("driverLibraryId");
        DriverLibrary driverLibrary = findById(driverLibraryId);
        if (driverLibrary == null) {
            return JsonUtil.getFail(ErrorCodeEnum.DATA_NOT_FOUND, "找不到对应的驱动数据!");
        }
        Chip chip = chipService.findById(driverLibrary.getChipId());
        if (chip == null) {
            return JsonUtil.getFail(ErrorCodeEnum.DATA_NOT_FOUND, "找不到对应的芯片数据!");
        }
        JSONObject driverData = parseJsonFile(data);
        if (driverData == null) {
            return JsonUtil.getFail(ErrorCodeEnum.IMPORT_CONTENT_ERROR);
        }
        String compatible = StringUtils.join(driverData.getJSONArray("compatible"), ",");
        if (isDuplicateByCondition(driverLibrary.getType(), driverLibrary.getChipId(), compatible, driverLibraryId)) {
            return JsonUtil.getFail(ErrorCodeEnum.DUPLICATE_DATA, "该芯片驱动范围已存在!");
        }
        Integer userId = currentUser.getUserId();
        driverLibrary.setCompatible(compatible);
        driverLibrary.setUpdateUserId(userId);
        updateById(driverLibrary);
        //删除旧驱动库数据
        deleteDriverInfo(driverLibraryId);
        //保存新驱动数据
        saveDriverInfo(chip, driverLibrary, driverData, userId);
        //修改驱动定义文件
        filesService.updateFiles(data.getJSONArray("driverDefinitionFiles"), userId, FileRelationTypeEnum.DRIVER_DEFINITION.getRelationTypeId(), driverLibraryId);
        List<RuleSet> ruleSetList = ruleSetService.findByProperty(RuleSet::getDriverLibraryId, driverLibraryId);
        return ruleSetService.getParameterConfigurationRuleSetList(ruleSetList);
    }
    /**
     * 添加驱动模板文件
     * @param data
     * @return
     */
    public JSONObject addDriverFiles(JSONObject data, Users currentUser){
        Integer driverLibraryId = data.getInteger("driverLibraryId");
        Integer relationTypeId = data.getInteger("relationTypeId");
        JSONArray driverFiles = data.getJSONArray("driverFiles");
        if (driverLibraryId == null || relationTypeId == null || driverFiles == null || driverFiles.isEmpty()){
            return JsonUtil.getFail(ErrorCodeEnum.INVALID_PARAM,"缺少参数,请检查!");
        }
        filesService.saveFiles(driverFiles,currentUser.getUserId(),relationTypeId,driverLibraryId);
        return JsonUtil.getSuccess("");
    }

    /**
     * 解析芯片驱动json文件
     * @param data
     * @return
     */
    public JSONObject parseJsonFile(JSONObject data){
        JSONArray driverDefinitionFiles = data.getJSONArray("driverDefinitionFiles");
        String jsonStr = null;
        if (driverDefinitionFiles != null && !driverDefinitionFiles.isEmpty()){
            String filePath = baseFilePath + driverDefinitionFiles.getJSONObject(0).getString("path").replaceFirst("uploads/", "");
            jsonStr = FileUtils.getStr(filePath);
        }
        return validateChipData(jsonStr);
    }

    /**
     * 验证芯片驱动json数据
     * @param jsonStr
     * @return
     */
    public JSONObject validateChipData(String jsonStr){
        JSONObject driverData = null;
        if (StringUtils.isNotBlank(jsonStr)){
            try {
                driverData = JSONObject.parseObject(jsonStr);
                JSONArray compatible = driverData.getJSONArray("compatible");
                JSONArray parameters = driverData.getJSONArray("parameters");
                JSONArray controlMode = driverData.getJSONArray("control_mode");
                if (compatible == null || parameters == null || controlMode == null){
                    return null;
                }
            } catch (JSONException e) {
                return null;
            }
        }
        return driverData;
    }

    /**
     * 保存驱动库驱动信息
     * @param chip
     * @param driverLibrary
     * @param driverData
     * @param userId
     */
    public void saveDriverInfo(Chip chip,DriverLibrary driverLibrary,JSONObject driverData,Integer userId){
        Integer chipId = chip.getChipId();
        Integer driverLibraryId = driverLibrary.getDriverLibraryId();
        JSONArray parameters = driverData.getJSONArray("parameters");
        RuleSet driverRuleSet = ruleSetService.createParameterConfigurationRuleSet(userId,"驱动配置",chip.getChipId());
        driverRuleSet.setType(RuleSetTypeEnum.DRIVER_CONFIGURATION);
        driverRuleSet.setDriverLibraryId(driverLibraryId);
        ruleSetService.save(driverRuleSet);
        Pattern relationalOperatorPattern = conditionService.getRelationalOperatorPattern();
        Map<Rule,List<Condition>> ruleToConditionListData = new HashMap<>();
        Map<Rule,Rule> dependenciesRuleToConfigurationRuleData = new HashMap<>();
        List<Rule> addRuleList = new ArrayList<>();
        List<Condition> addConditionList = new ArrayList<>();
        List<String> parameterConfigurationDataTypeList = ParameterConfigurationDataTypeEnum.getTypeList();

        List<ChipParameter> chipParameterList = new ArrayList<>();
        if (parameters != null && !parameters.isEmpty()){
            for (int i = 0; i < parameters.size(); i++) {
                JSONObject parameter = parameters.getJSONObject(i);
                ChipParameter chipParameter = parameter.toJavaObject(ChipParameter.class);
                chipParameter.setDriverLibraryId(driverLibraryId);
                chipParameter.setChipId(chipId);
                chipParameterList.add(chipParameter);
                List<Rule> ruleList = new ArrayList<>();
                String parameterName = chipParameter.getParameterName() == null ? "" : chipParameter.getParameterName();
                String symbol = chipParameter.getSymbol() == null ? "" : chipParameter.getSymbol();
                Rule dependenciesRule = ruleService.createDependenciesRule(userId, relationalOperatorPattern, ruleToConditionListData, addConditionList, chipParameter.getDependencies(), parameterName, driverRuleSet,null,symbol);
                Rule configurationRule = ruleService.createConfigurationRule(userId, addConditionList, parameterConfigurationDataTypeList, ruleToConditionListData, chipParameter.getDataType(), chipParameter.getValidValues(), parameterName, driverRuleSet,null,symbol);
                if(dependenciesRule != null){
                    ruleList.add(dependenciesRule);
                    if(configurationRule != null){
                        dependenciesRuleToConfigurationRuleData.put(dependenciesRule,configurationRule);
                    }
                }
                if(configurationRule != null){
                    ruleList.add(configurationRule);
                }
                addRuleList.addAll(ruleList);
            }
        }
        if (!chipParameterList.isEmpty()){
            //保存被控芯片参数信息
            chipParameterService.saveBatch(chipParameterList);
            //保存被控芯片参数属性定义信息
            formPropertyDefinitionService.insertFromChipParameters(chipParameterList);

            ruleSetService.addParameterConfigurationRuleSet(ruleToConditionListData, dependenciesRuleToConfigurationRuleData, addRuleList, addConditionList);
        }
        //生成被控芯片默认参数表单布局
        formLayoutService.generateLayoutByParameters(chip.getDisplayName() + "驱动-" + driverLibrary.getCompatible(),driverLibraryId, FormBusinessModuleEnum.SLAVE_CHIP_PARAMETER.getModuleId(),userId,chipParameterList);

        JSONArray controlMode = driverData.getJSONArray("control_mode");
        if (controlMode != null && !controlMode.isEmpty()){
            for (int i = 0; i < controlMode.size(); i++) {
                JSONObject controlModeData = controlMode.getJSONObject(i);
                ChipControlMode chipControlMode = controlModeData.toJavaObject(ChipControlMode.class);
                chipControlMode.setDriverLibraryId(driverLibraryId);
                chipControlMode.setChipId(chipId);
                //保存被控芯片控制模式信息
                chipControlModeService.save(chipControlMode);
                JSONArray requiredInterfaces = controlModeData.getJSONArray("required_interfaces");
                if (requiredInterfaces != null && !requiredInterfaces.isEmpty()){
                    for (int j = 0; j < requiredInterfaces.size(); j++) {
                        JSONObject controlModeInterface = requiredInterfaces.getJSONObject(j);
                        ChipControlModeInterface chipControlModeInterface = controlModeInterface.toJavaObject(ChipControlModeInterface.class);
                        chipControlModeInterface.setControlModeId(chipControlMode.getControlModeId());
                        //保存被控芯片控制模式所需接口信息
                        chipControlModeInterfaceService.save(chipControlModeInterface);
                        String[] interfaceType = controlModeInterface.getString("interface_type").split(",");
                        if (interfaceType.length > 0){
                            List<ChipControlModeInterfaceType> controlModeInterfaceTypeList = new ArrayList<>();
                            for (int k = 0; k < interfaceType.length; k++) {
                                ChipControlModeInterfaceType chipControlModeInterfaceType = new ChipControlModeInterfaceType();
                                chipControlModeInterfaceType.setControlModeInterfaceId(chipControlModeInterface.getControlModeInterfaceId());
                                chipControlModeInterfaceType.setInterfaceType(interfaceType[k]);
                                controlModeInterfaceTypeList.add(chipControlModeInterfaceType);
                            }
                            if (!controlModeInterfaceTypeList.isEmpty()){
                                //保存被控芯片控制模式接口类型信息
                                chipControlModeInterfaceTypeService.saveBatch(controlModeInterfaceTypeList);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 删除驱动库
     * @param data
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(JSONObject data){
        Integer driverLibraryId = data.getInteger("driverLibraryId");
        DriverLibrary driverLibrary = findById(driverLibraryId);
        if (driverLibrary != null){
            if (ChipTypeEnum.MASTER.getType().equals(driverLibrary.getType())){
                driverLibraryDirectoryService.deleteByDriverLibraryId(driverLibraryId);
            }
            if (ChipTypeEnum.SLAVE.getType().equals(driverLibrary.getType())){
                filesService.deleteFiles(Arrays.asList(FileRelationTypeEnum.DRIVER_DEFINITION.getRelationTypeId(),FileRelationTypeEnum.H_HEADER.getRelationTypeId(),FileRelationTypeEnum.C_SOURCE.getRelationTypeId()),driverLibraryId);
                deleteDriverInfo(driverLibraryId);
            }
            removeById(driverLibraryId);
        }
        return JsonUtil.getSuccess("");
    }

    /**
     * 删除驱动信息
     * @param driverLibraryId
     */
    public void deleteDriverInfo(Integer driverLibraryId){
        List<ChipParameter> parameterList = chipParameterService.findByProperty(ChipParameter::getDriverLibraryId,driverLibraryId);
        if (!parameterList.isEmpty()){
            //删除被控芯片参数数据
            chipParameterService.removeByIds(parameterList.stream().map(ChipParameter::getChipParameterId).collect(Collectors.toList()));
        }
        List<ChipControlMode> controlModeList = chipControlModeService.findByProperty(ChipControlMode::getDriverLibraryId,driverLibraryId);
        if (!controlModeList.isEmpty()){
            List<Integer> controlModeIds = controlModeList.stream().map(ChipControlMode::getControlModeId).collect(Collectors.toList());
            //删除被控芯片控制模式数据
            chipControlModeService.removeByIds(controlModeIds);
            List<ChipControlModeInterface> chipControlModeInterfaceList = chipControlModeInterfaceService.list(new QueryWrapper<ChipControlModeInterface>().lambda().in(ChipControlModeInterface::getControlModeId,controlModeIds));
            if (!chipControlModeInterfaceList.isEmpty()){
                List<Integer> controlModeInterfaceIds = chipControlModeInterfaceList.stream().map(ChipControlModeInterface::getControlModeInterfaceId).collect(Collectors.toList());
                //删除被控芯片控制模式接口数据
                chipControlModeInterfaceService.removeByIds(controlModeInterfaceIds);
                List<ChipControlModeInterfaceType> controlModeInterfaceTypeList = chipControlModeInterfaceTypeService.list(new QueryWrapper<ChipControlModeInterfaceType>().lambda().in(ChipControlModeInterfaceType::getControlModeInterfaceId,controlModeInterfaceIds));
                if (!controlModeInterfaceTypeList.isEmpty()){
                    //删除被控芯片控制模式接口类型数据
                    chipControlModeInterfaceTypeService.removeByIds(controlModeInterfaceTypeList.stream().map(ChipControlModeInterfaceType::getId).collect(Collectors.toList()));
                }
            }
        }
        List<RuleSet> ruleSetList = ruleSetService.findByProperty(RuleSet::getDriverLibraryId, driverLibraryId);
        List<Integer> ruleSetIdList = ruleSetList.stream().map(RuleSet::getRuleSetId).collect(Collectors.toList());
        ruleSetService.deleteByRuleSetIds(ruleSetIdList);
    }

    /**
     * 判断芯片驱动是否重复
     * @param chipType
     * @param chipId
     * @return
     */
    public Boolean isDuplicateByCondition(Integer chipType,Integer chipId,String compatible,Integer driverLibraryId){
        QueryWrapper<DriverLibrary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DriverLibrary::getType,chipType);
        queryWrapper.lambda().eq(DriverLibrary::getChipId,chipId);
        if (StringUtils.isNotBlank(compatible)){
            queryWrapper.lambda().eq(DriverLibrary::getCompatible,compatible);
        }
        if (driverLibraryId != null){
            queryWrapper.lambda().ne(DriverLibrary::getDriverLibraryId,driverLibraryId);
        }
        int count = count(queryWrapper);
        if (count > 0){
            return true;
        }
        return false;
    }


    /**
     * 根据主被控芯片ID,适配驱动库
     * @param data
     * @return
     */
    public JSONObject adaptiveDriverLibrary(JSONObject data){
        Integer masterChipId = data.getInteger("masterChipId");
        Integer slaveChipId = data.getInteger("slaveChipId");
        Chip masterChip = chipService.findById(masterChipId);
        if (masterChip == null){
            return JsonUtil.getFail(ErrorCodeEnum.DATA_NOT_FOUND,"找不到对应的主控芯片数据!");
        }
        Chip slaveChip = chipService.findById(slaveChipId);
        if (slaveChip == null){
            return JsonUtil.getFail(ErrorCodeEnum.DATA_NOT_FOUND,"找不到对应的被控芯片数据!");
        }
        List<DriverLibrary> driverLibraryList = findByProperty(DriverLibrary::getChipId,slaveChipId);
        if (driverLibraryList.isEmpty()){
            return JsonUtil.getFail(ErrorCodeEnum.DATA_OPERATION_DENY,"请添加被控芯片驱动程序!");
        }
        String masterCompatible = masterChip.getCompatible();
        Integer driverLibraryId = null;
        for (DriverLibrary driverLibrary : driverLibraryList){
            List<String> slaveCompatibleList = Arrays.asList(driverLibrary.getCompatible().split(","));
            if (slaveCompatibleList.contains(masterCompatible)){
                driverLibraryId = driverLibrary.getDriverLibraryId();
                break;
            }
        }
        if (driverLibraryId == null){
            return JsonUtil.getFail(ErrorCodeEnum.DATA_OPERATION_DENY,"被控驱动不能适配主控!");
        }
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,driverLibraryId);
    }

}
